#include "iwdg.h"

void IWDG_Init(uint16_t Tout)
{    
    //取消写保护
    IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
    //根据时间配置分频系数并计算溢出值
    if(Tout > 26214) Tout = 26214;
    if(Tout < 410)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_4);
        Tout = (Tout*40)/4;
    }
    else if(Tout < 820)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_8);
        Tout = (Tout*40)/8;
    }
    else if(Tout < 1639)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_16);
        Tout = (Tout*40)/16;
    }
    else if(Tout < 3277)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_32);
        Tout = (Tout*40)/32;
    }
    else if(Tout < 6554)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_64);
        Tout = (Tout*40)/64;
    }
    else if(Tout < 13108)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_128);
        Tout = (Tout*40)/128;
    }
    else if(Tout < 26215)
    {
        IWDG_SetPrescaler(IWDG_Prescaler_256);
        Tout = (Tout*40)/256;
    }
    //设置溢出值
    IWDG_SetReload(Tout);
    //重载
    IWDG_ReloadCounter();
    //使能看门狗
    IWDG_Enable();
}
